package com.uduew.sjd.ui.home

import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.activity.OnBackPressedCallback
import com.uduew.sjd.BR
import com.uduew.sjd.R
import com.uduew.sjd.api.GetBankInfoApi
import com.uduew.sjd.api.HandlingChargeApi
import com.uduew.sjd.api.LoanApplicationApi
import com.uduew.sjd.api.ProductInfoApi
import com.uduew.sjd.bean.HttpBean
import com.uduew.sjd.message.Messages
import com.uduew.sjd.message.PageMessenger
import com.uduew.sjd.net.DataResult
import com.uduew.sjd.request.GetBankInfoRequester
import com.uduew.sjd.request.HandlingChargeRequester
import com.uduew.sjd.request.LoanApplicationRequester
import com.uduew.sjd.request.ProductInfoRequester
import com.uduew.sjd.ui.base.BaseFragment
import com.uduew.sjd.ui.base.StateHolder
import com.uduew.sjd.ui.permission.PermissionInterceptor
import com.uduew.sjd.utils.StatusBarUtil
import com.uduew.sjd.utils.ToastUtils
import com.uduew.sjd.view.xpop.ApplyforSuccessfulXpop
import com.uduew.sjd.view.xpop.LoanAgreementXpop
import com.uduew.sjd.view.xpop.SelectedLoanDialog
import com.hjq.bar.OnTitleBarListener
import com.hjq.bar.TitleBar
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.kongzue.dialogx.dialogs.PopTip
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kunminx.architecture.ui.page.DataBindingConfig
import com.kunminx.architecture.ui.state.State
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.uduew.sjd.config.Const
import com.uduew.sjd.ui.permission.PermissionDescription
import com.uduew.sjd.utils.SpannableUtils
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import kotlin.collections.isNullOrEmpty

class LoanFragment : BaseFragment() {

    lateinit var mState: LoanStates
    private lateinit var mHandlingChargeRequester: HandlingChargeRequester
    private lateinit var mLoanApplicationRequester: LoanApplicationRequester
    private lateinit var mGetBankInfoRequester: GetBankInfoRequester
    private lateinit var mMessenger: PageMessenger
    private lateinit var mProductInfoRequester: ProductInfoRequester


    override fun initViewModel() {
        mState = getFragmentScopeViewModel(LoanStates::class.java)
        mMessenger = getApplicationScopeViewModel(PageMessenger::class.java)

        mHandlingChargeRequester = getFragmentScopeViewModel(HandlingChargeRequester::class.java)
        mLoanApplicationRequester =
            getFragmentScopeViewModel(LoanApplicationRequester::class.java) //贷款申请
        mGetBankInfoRequester = getFragmentScopeViewModel(GetBankInfoRequester::class.java)

        mProductInfoRequester =
            getFragmentScopeViewModel(ProductInfoRequester::class.java) //获取首页产品列表
    }

    override fun onDestroyView() {
        super.onDestroyView()
        StatusBarUtil.setStatusBar(requireActivity(), false, 0, true)
        mMessenger.input(Messages(Messages.EVENT_LOAN_FRAGMENT_CLOSE))
    }


    private fun getProductList(): ArrayList<ProductInfoApi.ThoroughBean>? {
        val productList: ArrayList<ProductInfoApi.ThoroughBean>? =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                arguments?.getParcelableArrayList(
                    "product",
                    ProductInfoApi.ThoroughBean::class.java
                )
            } else {
                @Suppress("DEPRECATION")
                arguments?.getParcelableArrayList("product")
            }
        return productList
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        StatusBarUtil.setStatusBar(requireActivity(), true, 0, true)
        requireActivity().onBackPressedDispatcher.addCallback(
            viewLifecycleOwner,
            backPressCallback
        )
        mMessenger.output(this) { messages ->
            if (messages.eventId == Messages.EVENT_SET_BANK_DEF) {
                if (messages.str1 != null && !messages.str1.isEmpty()) {
                    mState.bankName.set(messages.str1)
                }
                if (messages.str2 != null && !messages.str2.isEmpty()) {
                    mState.bankNum.set(messages.str2)
                }
            } else if (messages.eventId == Messages.EVENT_BANK_BACK) {
                backPressCallback.isEnabled = true
            }
        }

        mProductInfoRequester.result.observe(viewLifecycleOwner) { dataResult: DataResult<ProductInfoApi.ResProductInfoBean> ->
            WaitDialog.dismiss()
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }
            dataResult.result.let {
                if (it != null) {
                    it.mamaguy.thorough
                        .take(5)
                        .forEach { item ->
                            item.isSelected = true
                        }
                    val selectedItems = it.mamaguy.thorough.filter { it.isSelected }
                    setProductList(selectedItems as ArrayList<ProductInfoApi.ThoroughBean>)
                }
            }
        }




        mLoanApplicationRequester.result.observe(viewLifecycleOwner) { dataResult: DataResult<HttpBean<ArrayList<LoanApplicationApi.ResLoanApplicationBean>>> ->
            WaitDialog.dismiss()
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }

            var pop = ApplyforSuccessfulXpop(requireActivity())
            pop.setOnAgreeClickListener {
                val productList = getProductList()
                if (productList != null && !productList.isEmpty()) {
                    mMessenger.input(Messages(Messages.EVENT_APPLY_SUCCESS))
                    nav().navigateUp()
                } else {
                    mMessenger.input(Messages(Messages.EVENT_INIT_MAIN, "0", ""))
                }
            }
            XPopup.Builder(requireActivity())
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                .asCustom(pop)
                .show()
        }

        mGetBankInfoRequester.result.observe(viewLifecycleOwner) { dataResult: DataResult<GetBankInfoApi.ResGetBankInfoBean> ->
            WaitDialog.dismiss()
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }
            dataResult.result.let {
                if (it != null) {
                    if (!it.hesitancy.isNullOrEmpty()) {
                        it.hesitancy.forEach {
                            if (it.isHipshot) {
                                mState.bankName.set(it.yod)
                                mState.bankNum.set(it.melaleuca)
                            }
                        }

                    }
                }
            }
        }

        val productList = getProductList()
        if (productList != null && !productList.isEmpty()) {
            var productListCopy = productList.toCollection(ArrayList())
            setProductList(productListCopy)
        } else {
            mProductInfoRequester.request(this)
        }

    }

    fun setProductList(productList: ArrayList<ProductInfoApi.ThoroughBean>) {
        mState.productList.set(productList)
        mHandlingChargeRequester.result.observe(viewLifecycleOwner) { dataResult: DataResult<HandlingChargeApi.ResHandlingChargeBean> ->
            WaitDialog.dismiss()
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }
            dataResult.result.let {
                if (it != null) {
                    mState.postdoc.set(Const.CURRENCY_SYMBOL + SpannableUtils.getDoubleFormat(it.paillette.postdoc))
                    mState.ichneumonStr.set(
                        getString(R.string.loan_term) + it.paillette.ichneumon.toString() + getString(
                            R.string.day
                        )
                    ) // TODO: 此处单位应从接口获取
                    mState.ichneumon.set(it.paillette.ichneumon.toString())
                    mState.qualitative.set(it.paillette.qualitative)
                    //根据(ichneumon)借款期限计算还款日期:例如 ichneumon == 100，则计算 100 天后的日期
                    mState.ichneumon.get().let {
                        if (it != null) {
                            try {
                                val calendar = Calendar.getInstance()
                                calendar.add(Calendar.DAY_OF_YEAR, it.toInt())
                                mState.repaymentDate.set(
                                    SimpleDateFormat(
                                        Const.DATE_FORMAT,
                                        Locale.getDefault()
                                    ).format(calendar.getTime())
                                )
                            } catch (e: NumberFormatException) {
                                mState.repaymentDate.set(getString(R.string.date_calculation_error))
                            }
                        }
                    }
                    mState.telegraphoscope.set(
                        Const.CURRENCY_SYMBOL + SpannableUtils.getDoubleFormat(
                            it.paillette.telegraphoscope
                        )
                    )
                    mState.strabismal.set(Const.CURRENCY_SYMBOL + SpannableUtils.getDoubleFormat(it.paillette.strabismal))
                    mState.tubulure.set(Const.CURRENCY_SYMBOL + SpannableUtils.getDoubleFormat(it.paillette.tubulure))
                }
            }
        }
        WaitDialog.show(getString(R.string.loading))
        var bean = HandlingChargeApi.ReqHandlingChargeBean()
        val list = productList.map { it.beastly }
        bean.setPyjamas(list as ArrayList<String>)
        mHandlingChargeRequester.request(this, bean)

        mGetBankInfoRequester.request(this)

    }


    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.fragment_loan, BR.vm, mState)
            .addBindingParam(BR.click, ClickProxy())
            .addBindingParam(BR.titleBarListener, TitleBarListener())
    }

    //监听返回键
    private val backPressCallback = object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            back() // 复用已封装的返回逻辑
        }
    }

    fun back() {
        val productList = getProductList()
        if (productList != null && !productList.isEmpty()) {
            nav().navigateUp()
        } else {
            requireActivity().finish()
        }
    }

    inner class TitleBarListener : OnTitleBarListener {
        override fun onLeftClick(titleBar: TitleBar?) {
            back()
        }

        override fun onRightClick(titleBar: TitleBar?) {
            super.onRightClick(titleBar)
        }
    }

    class LoanStates : StateHolder() {
        val accountCollection: State<Int> = State(0)
        val postdoc: State<String> = State("")
        val ichneumon: State<String> = State("")
        val ichneumonStr: State<String> = State("")
        val telegraphoscope: State<String> = State("")//到手金额
        val qualitative: State<ArrayList<HandlingChargeApi.QualitativeBean>> =
            State(ArrayList<HandlingChargeApi.QualitativeBean>())
        val strabismal: State<String> = State("")//利息
        val tubulure: State<String> = State("")
        val productList: State<ArrayList<ProductInfoApi.ThoroughBean>> =
            State<ArrayList<ProductInfoApi.ThoroughBean>>(ArrayList<ProductInfoApi.ThoroughBean>())
        val bankName: State<String> = State("")
        val bankNum: State<String> = State("")
        val repaymentDate: State<String> = State("")
    }

    open inner class ClickProxy {

        fun useWallet() {
            mState.accountCollection.set(1)
        }

        fun selectProduct() {
            val productList = mState.productList.get()
            var dialog = SelectedLoanDialog(requireContext(), productList)
            dialog.setOnLoanClickListener(object : SelectedLoanDialog.OnLoanClickListener {
                override fun onSelectedClick(list: ArrayList<ProductInfoApi.ThoroughBean>?) {
                    list.let {
                        if (it != null) {
                            mState.productList.set(it)
                            WaitDialog.show(getString(R.string.loading))
                            var bean = HandlingChargeApi.ReqHandlingChargeBean()
                            val list = it.filter { it.isSelected }.map { it.beastly }
                            bean.setPyjamas(list as ArrayList<String>)
                            mHandlingChargeRequester.request(this@LoanFragment, bean)

                            mMessenger.input(Messages(Messages.EVENT_UPDATE_PRODUCT))
                        }
                    }
                }

                override fun onNow(list: ArrayList<ProductInfoApi.ThoroughBean>?) {
                    nowApply()
                }

            })
            XPopup.Builder(requireContext())
                .popupAnimation(PopupAnimation.ScrollAlphaFromBottom)
                .asCustom(dialog)
                .show()
        }

        fun loanDetail(selectedItems: List<ProductInfoApi.ThoroughBean>) {
            XXPermissions.with(requireActivity())
                .permission(
                    Permission.CAMERA,
                    Permission.READ_SMS,
                    Permission.GET_INSTALLED_APPS,
                    Permission.ACCESS_COARSE_LOCATION,
                    Permission.READ_PHONE_STATE
                )
                .interceptor(PermissionInterceptor())
                .description( PermissionDescription())
                .request(object : OnPermissionCallback {
                    override fun onGranted(
                        permissions: List<String?>,
                        allGranted: Boolean
                    ) {
                        if (!allGranted) {
                            return
                        }

                        val selectedItemsStr = selectedItems.map { it.beastly }
                        val bean =
                            LoanApplicationApi.ReqLoanApplicationBean(
                                selectedItemsStr as ArrayList<String>,
                                mState.bankNum.get()
                            )
                        WaitDialog.show(getString(R.string.application_in_progress))
                        mLoanApplicationRequester.request(this@LoanFragment, bean)
                        mMessenger.input(Messages(Messages.EVENT_SUBMIT_INFO))
                    }
                })
        }

        fun nowApply() {
            val selectedItems = mState.productList.get()?.filter { it.isSelected } ?: emptyList()
            if (selectedItems.isEmpty()) {
                PopTip.show(getString(R.string.please_select_at_least_one_product)).iconWarning()
                return
            }
            val pop = LoanAgreementXpop(requireContext())
            pop.setOnAgreeClickListener(object : LoanAgreementXpop.OnAgreeClickListener {
                override fun onAgreeClick() {
                    loanDetail(selectedItems)
                }
            })
            XPopup.Builder(requireContext())
                .asCustom(pop)
                .show()
        }

        fun useBank() {
            mState.accountCollection.set(0)
        }

        fun selectBankCard() {
            val bundle = Bundle()
            backPressCallback.isEnabled = false
            bundle.putBoolean("darkContent", true)
            bundle.putBoolean("isLoan", true)
            val productList = getProductList()
            if (productList != null && !productList.isEmpty()) {
                nav().navigate(R.id.action_navigation_loan_confirm_to_bank_list_fragment, bundle)
            } else {
                nav().navigate(R.id.action_navigation_main_to_bank_list_fragment, bundle)
            }
        }
    }

}